package com.ch01.ex21;

import java.util.concurrent.TimeUnit;

/**
 * Created by zc on 2016/1/27.
 */
public class Main {

    public static void main(String[] args){
        ThreadGroup threadGroup = new ThreadGroup("Searcher");
        Resut resut = new Resut();
        SearchTesk searchTesk = new SearchTesk(resut);

        for(int i=0; i<5; i++){
            Thread thread = new Thread(threadGroup,searchTesk);
            thread.start();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.printf("Number of Threads: %s\n",
                threadGroup.activeCount());
        System.out.printf("Information about the Thread Group\n");
        threadGroup.list();

        Thread[] threads = new Thread[threadGroup.activeCount()];
        threadGroup.enumerate(threads);
        for(int i=0; i<threadGroup.activeCount(); i++){
            System.out.printf("Thread %s: %s\n",
                    threads[i].getName(),threads[i].getState());
        }

        waitFinish(threadGroup);

        // 中断
        threadGroup.interrupt();
    }

    private static void waitFinish(ThreadGroup threadGroup){
        while(threadGroup.activeCount()>9){
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
